package com.xaicode.learn.netty.http;

import cn.hutool.core.util.ArrayUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.net.URI;

/**
 * @author Locker xaicode@sina.com
 * @version 1.0
 * @date 2021/6/15 0015 23:54
 */
@Slf4j
public class NettyHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    final String[] ignoreUri = new String[]{
            "/favicon.ico"
    };

    // read client msg
    // called for each message <T>, current is HttpObject
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        if (msg instanceof HttpRequest) {
            log.info("SelfNettyHttpServerHandler get msg with type [{}] from client [{}]",
                    msg.getClass(), ctx.channel().remoteAddress());

            // ignore uri check
            HttpRequest httpRequest = (HttpRequest) msg;
            URI uri = new URI(httpRequest.uri());
            if (shouldIgnore(uri)) {
                log.info("get ignore uri [{}], pass client [{}] request", uri.getPath(), ctx.channel().remoteAddress());
                return;
            }

            // response content
            ByteBuf responseContent = Unpooled.copiedBuffer("SelfNettyHttpServerHandler response at " + System.currentTimeMillis(), CharsetUtil.UTF_8);
            // build http response
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, responseContent);
            // header
            // content-type: text/plain
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.TEXT_PLAIN);
            // content-length: n
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, responseContent.readableBytes());

            // send response
            ctx.writeAndFlush(response);
        }
    }

    private boolean shouldIgnore(URI uri) {
        return ArrayUtil.contains(ignoreUri, uri.getPath());
    }
}
